# coding=utf-8
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_xml.parsers import XMLParser

from fe_api.transcript import forms
from fe_api.transcript.utils import view_funcs


# 微信回调的Content-Type为 text/xml，而非 application/xml
XMLParser.media_type = "text/xml"


class ConfigList(APIView):

    authentication_classes = (SessionAuthentication,)
    # permission_classes = (IsAuthenticated,)
    permission_classes = (AllowAny,)

    def get(self, request):
        """
        获取抄写配置
        """
        config_list = view_funcs.get_config_list()
        return Response({
                "status": 200,
                "msg": "success",
                "data": config_list,
            })


class OrderList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, sutra_edition_id):
        """
        提交抄写订单
        """
        form = forms.CreateOrder(request.data)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        data = form.cleaned_data
        order_data = view_funcs.create_order(
            sutra_edition_id, request.user,
            data["typeset_id"], data["material_id"],
            data["bind_id"], data["font_color_id"])

        if not order_data:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": order_data,
        })


class OrderPreview(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, sutra_edition_id):
        """
        获取订单预览信息
        """
        form = forms.GetOrderPreview(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        data = form.cleaned_data
        preview_data = view_funcs.get_order_preview(
            sutra_edition_id, request.user,
            data["typeset_id"], data["material_id"],
            data["bind_id"], data["font_color_id"])

        if not preview_data:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": preview_data,
        })


class WechatPayNotify(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (AllowAny,)
    parser_classes = (XMLParser,)

    def post(self, request):
        """
        微信支付回调
        """
        if not view_funcs.check_wechat_notify_sign(request.data):
            return Response({
                "status": 403,
                "msg": "forbidden",
            })

        order_id = request.data.get("out_trade_no")
        is_success = view_funcs.finish_pay(order_id)
        if not is_success:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
        })


class VowList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取发愿文列表
        """
        try:
            offset = int(request.query_params.get("offset", 0))
            limit = int(request.query_params.get("limit", 10))
        except ValueError:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        vow_list = view_funcs.get_vow_list(offset, limit)
        return Response({
            "status": 200,
            "msg": "success",
            "data": vow_list,
        })


class Vow(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def put(self, request, user_transcription_id):
        """
        设置抄写发愿文
        """
        vow_text = request.data.get("vow_text")
        if not vow_text:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        is_success = view_funcs.update_vow(
            request.user, user_transcription_id, vow_text)
        if not is_success:
            return Response({
                "status": 403,
                "msg": "forbidden",
            })

        return Response({
            "status": 200,
            "msg": "success",
        })

    def get(self, request, user_transcription_id):
        """
        获取抄写发愿文
        """
        vow_text = view_funcs.get_vow(request.user, user_transcription_id)
        if vow_text is False:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": {
                "vow_text": vow_text,
            },
        })


class Progress(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, user_transcription_id):
        """
        获取抄写进度
        """
        progress_data = view_funcs.get_progress(
            request.user, user_transcription_id)
        if progress_data is None:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        if progress_data is False:
            return Response({
                "status": 410,
                "msg": "gone",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": progress_data,
        })


class PageData(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (AllowAny,)

    def get(self, request, sutra_edition_id, page_num):
        """
        获取抄写页数据
        """
        user_transcription_id = request.query_params.get(
            "user_transcription_id")

        page_data = view_funcs.get_page_data(
            sutra_edition_id, page_num, user_transcription_id)
        if not page_data:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": page_data
        })


class SubmitChar(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, user_transcription_id, page_num, index):
        """
        提交抄写字
        """
        is_success = view_funcs.submit_char(
            request.user, int(user_transcription_id),
            int(page_num), int(index))
        if not is_success:
            return Response({
                "status": 403,
                "msg": "forbidden",
            })

        return Response({
            "status": 200,
            "msg": "success",
        })


class Finish(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, user_transcription_id):
        """
        完成抄写
        """
        signature_img = request.FILES.get("signature_img")
        signature_text = request.data.get("signature_text")
        if not signature_img and not signature_text:
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        is_success, finish_data = view_funcs.finish_transcription(
            request.user, user_transcription_id,
            signature_img, signature_text)

        if not is_success:
            return Response({
                "status": 403,
                "msg": "forbidden",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": finish_data,
        })


class SutraEditionList(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        """
        获取抄写经书版本列表
        """
        form = forms.GetSutraEditionList(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        data = form.cleaned_data
        editions = view_funcs.get_sutra_editions(
            request.user, data["type"], data["offset"], data["limit"])

        return Response({
            "status": 200,
            "msg": "success",
            "data": editions,
        })


class UserTranscriptionDetail(APIView):

    authentication_classes = (SessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def get(self, request, user_transcription_id):
        """
        获取抄写经书版本详情
        """
        form = forms.GetSutraEditionDetail(request.query_params)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        data = form.cleaned_data
        detail_data = view_funcs.get_user_transcription_detail(
            request.user, user_transcription_id, data["type"])
        if not detail_data:
            return Response({
                "status": 404,
                "msg": "not found",
            })

        return Response({
            "status": 200,
            "msg": "success",
            "data": detail_data,
        })
